import json
import os
from fastapi.responses import FileResponse
from fastapi import FastAPI,Request,Response
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from JianGuan import create_JianGuan_word

down_load_api = "http://10.85.2.51:8115/down_load/"
word_path = "./word/"

def main():
    app = FastAPI()

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"], #允许的源
        allow_credentials=True, #允许携带 Cookie 或其他凭证
        allow_methods=["*"], #允许的请求方法
        allow_headers=["*"], #允许的请求头
    )

    @app.get("/JianGuan")
    async def JianGuan(request: Request):
        data = await request.json()
        need_keys = ["data1_7", "data1_8", "data1_9", "data2_2_1", "data2_2_2",\
                     "data2_3_1", "data2_3_2", "data2_4", "data2_5", "data2_6_1",\
                     "data2_6_2", "jh", "cookie"]
        #检查生成word文档的参数是否都存在
        if not all(need_key in data for need_key in need_keys):
            return Response(status_code=404,content="{'error': '所需参数不匹配'}")

        file_name = create_JianGuan_word(**data)
        res_josn = {"download": down_load_api + file_name}
        res_json = json.dumps(res_josn)
        return Response(status_code=200,content=res_json)

    @app.get("/down_load/{file_name}")
    async def down_load(resquest: Request):
        file_name = str(resquest.url).split("/")[-1]
        file_path = word_path + file_name
        #文件不存在
        if not os.path.exists(file_path):
            return Response(status_code=404,content="{'error': '文件不存在，可能超过了可下载时间'}")
        headers = {"Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}
        return FileResponse(file_path, headers=headers, filename=file_name)

    return app

if __name__ == "__main__":
    app = main()
    api_host = os.environ.get("API_HOST", "0.0.0.0")
    api_port = int(os.environ.get("API_PORT", "8115"))
    uvicorn.run(app, host=api_host, port=api_port, )